package com.geekyang.rabbitmqapi.confirmlistener;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author ccyang
 * @date 2018/10/14 10:58
 * confirm 确认机制：消费者
 */
public class Consumer {

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {

        //1 创建 ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("39.106.128.50");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        //2 创建 Connection
        Connection connection = connectionFactory.newConnection();

        //3 通过 Connection 创建 Channel
        Channel channel = connection.createChannel();

        String exchangeName = "test_confirm_exchange";
        String queueName = "test_confirm_queue";
        String routingKey = "confirm.#";

        //4 声明交换机和队列，然后进行绑定设置，最后制定路由key
        channel.exchangeDeclare(exchangeName,"topic", true);
        channel.queueDeclare(queueName, true, false, false, null);
        channel.queueBind(queueName, exchangeName, routingKey);

        //5 创建消费者
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);
        channel.basicConsume(queueName, true, queueingConsumer);

        while(true){
            QueueingConsumer.Delivery delivery = queueingConsumer.nextDelivery();
            String msg = new String(delivery.getBody());

            System.err.println(msg);
        }
    }
}
